package com.zhen.controller;

import com.zhen.domain.User;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: zhen-desktop
 * Date: 2019/1/25
 * Time: 23:12
 */
@Controller
public class UserController {

    @RequestMapping("/{formName}")
    public String loginForm(@PathVariable String formName,String request_locale, Model model,HttpServletRequest request){
        System.out.println("request_locale = " + request_locale);
        if(request_locale != null){
            if("zh_CN".equals(request_locale)){
                Locale locale = new Locale("zh","CN");
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
            }else if("en_US".equals(request_locale)){
                Locale locale = new Locale("en","US");
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
            }else{
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, LocaleContextHolder.getLocale());
            }
        }
        User user = new User();
        model.addAttribute(user);
        return formName;
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@ModelAttribute @Validated User user, Model model, HttpServletRequest request){
        if(user.getLoginname() != null && user.getLoginname().equals("fkit")
                && user.getPassword() != null && user.getPassword().equals("123456")){
            RequestContext requestContext = new RequestContext(request);
            String username = requestContext.getMessage("username");
            user.setUsername(username);
            model.addAttribute(user);
            return "success";
        }
        return "error";
    }
}
